package com.hyh.admin.recommend;

import com.hyh.admin.domain.resources.Resources;
import com.hyh.admin.service.IResourcesCollectService;
import com.hyh.admin.service.IResourcesViewsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class ScoreCalculatorService {

    @Autowired
    private IResourcesCollectService resourcesCollectService;

    @Autowired
    private IResourcesViewsService resourcesViewsService;

    @Autowired
    private UserProfileService userProfileService;

    /**
     * 更新用户对某课程的评分，并返回最新的用户信息
     */
    public void updateCourseScore(UserProfile userProfile, String courseId, String action) {
        Map<String, Double> ratedCourses = userProfile.getRatedCourses();
        if (ratedCourses == null) {
            ratedCourses = new HashMap<>();
            userProfile.setRatedCourses(ratedCourses);
        }

        // 计算权重
        int weight = getWeight(action);

        // 旧评分
        double oldScore = ratedCourses.getOrDefault(courseId, Double.parseDouble("0"));

        // 计算新评分
        double newScore;
        if (oldScore > 0) {
            // 旧评分存在，则加权平均（使用小数计算）
            newScore = oldScore + (10.0 - oldScore) * (weight / 10.0);
        } else {
            // 旧评分不存在，赋默认评分
            newScore = weight * 10.0 / 6.0;
        }


        // 评分最大不超过10
        newScore = Math.min(newScore, 10);


        // 更新评分
        ratedCourses.put(courseId, newScore);

        // **更新收藏记录**
        List<String> likedCourses = new ArrayList<>();
        for (Resources resources : resourcesCollectService.selectResourcesCollect(userProfile.getUser().getId())) {
            likedCourses.add(resources.getId().toString());
        }
        userProfile.setLikedCourses(likedCourses);

        // **更新浏览记录

        List<String> browsedCourses = new ArrayList<>();
        for (Resources resources : resourcesViewsService.selectResourcesViewsByUserId(userProfile.getUser().getId())) {
            browsedCourses.add(resources.getId().toString());
        }
        userProfile.setBrowsedCourses(browsedCourses);

        userProfile.setRecommendedCourses(userProfile.getRecommendedCourses());


        // **更新用户画像**
        userProfileService.saveUserProfile(userProfile);
    }

    /**
     * 计算课程行为的权重
     */
    private int getWeight(String action) {
        switch (action) {
            case "liked":
                return 2; // 收藏权重高
            case "browsed":
                return 1; // 浏览权重低
            case "clicked":
                return 1; // 点击权重适中
            default:
                return 1; // 其他行为默认权重
        }
    }
}
